import { nextTick } from 'vue'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { ElNotification } from 'element-plus'

let stompClient = null

// 连接 WebSocket
export const connectSocket = () => {
  const token = localStorage.getItem("token"); // 从 localStorage 获取 token
  if (!token) {
    console.error('No token found in localStorage')
    return
  }

  const socket = new SockJS('http://localhost:8080/ws-login') // 后端接口
  stompClient = Stomp.over(socket)

  // 连接时传递 token 作为连接头
  stompClient.connect(
    { satoken: token },  // 假设 token 存储在 localStorage 中
    () => {
      console.log('🟢 WebSocket 连接成功')

      // 订阅登录广播
      stompClient.subscribe('/topic/login', (message) => {
        const msg = message.body
        ElNotification({
          title: '用户登录通知',
          message: msg,
          position: 'bottom-right',
        })
      })
    },
    (error) => {
      console.error('WebSocket 连接失败:', error)
    }
  )
}

// 关闭 WebSocket 连接
export const disconnectSocket = () => {
  if (stompClient !== null) {
    stompClient.disconnect(() => {
      console.log('🔴 WebSocket 连接已断开')
    })
  } else {
    console.log('没有活跃的 WebSocket 连接')
  }
}

// 在 onMounted 中使用 nextTick 确保在页面渲染完成后启动 WebSocket 连接
onMounted(async () => {
  // 等待页面完全渲染后，再启动 WebSocket 连接
  await nextTick(() => {
    connectSocket()
  })
})